package com.juneng.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.juneng.common.R;
import com.juneng.dto.AfterSalesServiceRequest;
import com.juneng.dto.OrderMsgQueryDto;
import com.juneng.entity.OrderMsg;
import com.juneng.entity.OrderRefund;
import com.juneng.service.IOrderMsgService;
import com.juneng.service.IOrderRefundService;
import com.juneng.utils.ExcelUtil;
import com.juneng.utils.Func;

import java.io.*;
import java.net.URLEncoder;
import java.rmi.server.ExportException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.juneng.utils.PayUtil;
import com.juneng.utils.wechat.XMLUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jdom2.JDOMException;
import org.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.juneng.entity.OrderUser;
import com.juneng.dto.OrderUserDto;
import com.juneng.dto.OrderUserQueryDto;
import com.juneng.vo.OrderUserVo;
import com.juneng.service.IOrderUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户订单表 控制器
 *
 * @author zds
 * @since 2021-07-26
 */
@RestController
@AllArgsConstructor
@RequestMapping("orderUser/v1")
@Api(tags = "用户订单表相关接口")
@Slf4j
public class OrderUserController {

    private IOrderUserService orderUserService;

    private IOrderMsgService orderMsgService;

    private IOrderRefundService iOrderRefundService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperation(value = "详情", notes = "传入id")
    public R<OrderUser> detail(Integer id) {
        OrderUser detail = orderUserService.getById(id);
        return R.success(detail);
    }

    /**
     * 分页 用户订单表
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页", notes = "传入orderUser")
    public R<IPage<OrderUserVo>> page(OrderUserQueryDto dto) {
        IPage<OrderUserVo> pages = orderUserService.page(dto);
        return R.success(pages);
    }

    @PostMapping("/export")
    @ApiOperation(value = "导出excel")
    public void export(HttpServletResponse response, @RequestBody OrderUserQueryDto dto) {
        List<String> titleList = Arrays.asList(
                "序号",
                "内部订单号",
                "支付订单号",
                "支付方式",
                "订单金额",
                "支付金额",
                "收货人电话",
                "收货地址",
                "收货详细地址",
                "订单进度",
                "商品信息",
                "下单时间"
        );
        List<List<Object>> dataList = new ArrayList<>();
        List<OrderUserVo> exportOrder = orderUserService.getOrderUserList(dto);
//        IPage<OrderUserVo> pages = orderUserService.page(dto);
//        List<OrderUserVo> exportOrder = pages.getRecords();
      //  List<OmsOrderVo> exportOrder = omsOrderService.getExportOrder(dto);
        for (OrderUserVo omsOrderVo : exportOrder) {
            ArrayList<Object> list = new ArrayList<>();
            list.add(omsOrderVo.getInternalOrder());
            list.add(omsOrderVo.getPayOrder());
            if (omsOrderVo.getPaymentType() == 0){
                list.add("支付宝");
            }else {
                list.add("微信");
            }
            list.add(omsOrderVo.getTotalAmount());
            list.add(omsOrderVo.getPayOrder());
            list.add(omsOrderVo.getConsigneePhone());
            list.add(omsOrderVo.getConsigneeAddress());
            list.add(omsOrderVo.getConsigneeAddressDetail());
            switch (omsOrderVo.getStatus()){
                //`status` int(1) DEFAULT NULL COMMENT '订单状态：0->待付款； 2->待发货；3->已发货；4->待评价；5->已关闭；6->无效订单；10->待退货；11->已退货 12 ->已退款',
                case 0 : list.add("待付款"); break;
                case 2 : list.add("待发货"); break;
                case 3 : list.add("已发货");break;
                case 4 : list.add("待评价");break;
                case 5 : list.add("已关闭");break;
                case 6 : list.add("无效订单");break;
                case 10 : list.add("待退货");break;
                case 11 : list.add("已退货");break;
                case 12 : list.add("已退款");break;
            }
            //商品信息
            List<OrderMsg> product = omsOrderVo.getProduct();
            StringBuffer stringBuffer = new StringBuffer();
            if (product.size() != 0){
                for (OrderMsg orderMsg : product) {
                    stringBuffer.append("商品名字："+orderMsg.getBookName()).append("/").append("价格："+orderMsg.getBookPrice()).append("数量；"+orderMsg.getOrderCount()).append("----");
                }
            }
            list.add(stringBuffer);
            list.add(omsOrderVo.getCreateTime());
            dataList.add(list);
        }
        ExcelUtil.uploadExcelAboutUser(response, "order.xlsx", titleList, dataList);
    }

    @PostMapping("/orderDownload")
    @ApiOperation(value = "订单下载", notes = "传入orderUser")
    @ResponseBody
    public void orderDownload(OrderUserQueryDto dto,HttpServletResponse response) {
     //   IPage<OrderUserVo> pages = orderUserService.orderDownload(dto);
         orderUserService.orderDownload(dto,response);
    }
    @RequestMapping(value = "/companyExcel",method = RequestMethod.POST)
    @ResponseBody
    public void exportCompanyExcel(OrderUserQueryDto dto,HttpServletResponse response) {
        IPage<OrderUserVo> pages = orderUserService.page(dto);
        List<OrderUserVo> records = pages.getRecords();
        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("委托方信息列表");
            HSSFRow row = null;
            row = sheet.createRow(0);
            row.setHeight((short) (30 * 20));
            row.createCell(0).setCellValue("委托方信息列表");
            CellRangeAddress rowRegion = new CellRangeAddress(0, 0, 0, 2);
            sheet.addMergedRegion(rowRegion);
            row = sheet.createRow(1);
            row.setHeight((short) (22.50 * 20));//设置行高
            row.createCell(0).setCellValue("内部订单号");//为第三个单元格设值
            row.createCell(1).setCellValue("支付订单号");
            row.createCell(2).setCellValue("支付方式");
            row.createCell(3).setCellValue("订单金额");
            row.createCell(4).setCellValue("支付金额");
            row.createCell(5).setCellValue("收货人电话");
            row.createCell(6).setCellValue("收货地址");
            row.createCell(7).setCellValue("收货详细地址");
            row.createCell(8).setCellValue("订单进度");
            row.createCell(9).setCellValue("商品详细");
            for (int i = 0; i < records.size(); i++) {
                row = sheet.createRow(i + 2);
                row.createCell(0).setCellValue(records.get(i).getInternalOrder());//内部订单号
                row.createCell(1).setCellValue(records.get(i).getPayOrder());//支付订单号
                row.createCell(2).setCellValue(records.get(i).getStatus());//支付方式
                row.createCell(3).setCellValue(records.get(i).getTotalAmount().toString());//订单金额
                row.createCell(4).setCellValue(records.get(i).getPayAmount().toString());//支付金额
                row.createCell(5).setCellValue(records.get(i).getConsigneePhone());//收货人电话
                row.createCell(6).setCellValue(records.get(i).getConsigneeAddress());//收货地址
                row.createCell(7).setCellValue(records.get(i).getConsigneeAddressDetail());//收货详细地址
                row.createCell(8).setCellValue(records.get(i).getStatus());//订单进度
                row.createCell(9).setCellValue(records.get(i).getProduct().toString()); //商品详情]
            }
            sheet.setDefaultRowHeight((short) (16.5 * 20));
            //列宽自适应
            for (int i = 0; i <= 13; i++) {
                sheet.autoSizeColumn(i);
            }
            String title= "company";
            String  fileName = new String(title.getBytes("GB2312"), "ISO_8859_1");
            fileName = URLEncoder.encode(fileName,"utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            OutputStream os = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment;filename="+fileName+".xls");//默认Excel名称
            wb.write(os);
            os.flush();
            os.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 列表 用户订单表 拦截器
     */
    @GetMapping("/list")
    @ApiOperation(value = "不分页", notes = "传入orderUser")
    public R<List<OrderUser>> list(OrderUserQueryDto dto) {
        List<OrderUser> list = orderUserService.list(dto);
        return R.success(list);
    }

    /**
     * 新增 用户订单表
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增", notes = "传入orderUser")
    public R save(@RequestBody OrderUserDto dto) {
        return R.success(orderUserService.save(dto));
    }

    /**
     * 修改 用户订单表
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改", notes = "传入orderUser")
    public R update(@RequestBody OrderUserDto dto) {
        return R.success(orderUserService.updateById(dto));
    }

    /**
     * 删除 用户订单表  refund
     */
    @DeleteMapping("/remove")
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.success(orderUserService.deleteLogic(Func.toIntList(ids)));
    }
    //Referrer Policy: no-referrer
    @ApiOperation(value = "app退款售后服务")
    @RequestMapping(value = "afterSalesService", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public R<?> AfterSalesServiceRequest(HttpServletRequest request, HttpServletResponse response,@RequestBody AfterSalesServiceRequest afterSalesServiceRequest) {
        return orderUserService.AfterSalesServiceRequest(request,response,afterSalesServiceRequest);
    }

    /**
     * 接收微信退款成功通知
     * (empty list or set)
     * @param request
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "app微信支付回调接口")
    @RequestMapping(value = "/getAppWxPay")
    public void getnotify(HttpServletRequest request, HttpServletResponse response)
            throws IOException, JDOMException {
        log.info("****************************************微信退款回调函数被调用******************************");
        PrintWriter writer = response.getWriter();
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> map = null;
        /**
         * 解析微信通知返回的信息 router lay
         */
        map = XMLUtil.doXMLParse(result);
        if (map != null) {
            if (map.get("return_code") != null) {
                // 若支付成功，则告知微信服务器收到通知
                if (map.get("return_code").equals("SUCCESS")) {
                     //修改退款订单状态
                    Integer integer1 =1 ;
                    OrderRefund orderRefund = new OrderRefund();
                   // iOrderRefundService.updateOrderRefund()
                    if (integer1 ==1){
                        log.info("微信订单号" + map.get("transaction_id") + "商户订单号" + map.get("out_trade_no") + "订单记录成功");
                    }else {
                        log.info("微信订单号" + map.get("transaction_id") + "商户订单号" + map.get("out_trade_no") + "订单记录失败");
                    }
                    //判断通知是否已处理，若已处理，则不予处理
                    String notifyStr = XMLUtil.setXML("SUCCESS", "OK");
                    writer.write(notifyStr);
                    writer.flush();
                }
            }
        }
    }
}
